package com.caseprocessing.demo;

import com.caseprocessing.config.AIConfig;
import com.caseprocessing.enhanced.ComplianceModels.*;
import com.caseprocessing.integration.AIEnhancedSystemIntegrator;
import com.caseprocessing.integration.IntegrationModels.*;
import com.caseprocessing.interface.ConversationModels.*;
import com.caseprocessing.model.CaseDocument;
import com.caseprocessing.model.DocumentType;

import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * AI增强系统演示示例
 * 展示系统的完整功能和使用方法
 */
public class SystemDemoExample {
    
    private final AIEnhancedSystemIntegrator systemIntegrator;
    private final AIConfig config;
    
    public SystemDemoExample(String siliconFlowApiKey) {
        this.config = AIConfig.getInstance();
        
        // 如果提供了API密钥，则设置到配置中
        if (siliconFlowApiKey != null && !siliconFlowApiKey.trim().isEmpty()) {
            config.setApiKey(siliconFlowApiKey);
        }
        
        this.systemIntegrator = new AIEnhancedSystemIntegrator(siliconFlowApiKey);
    }
    
    /**
     * 使用配置文件中的API密钥创建演示
     */
    public SystemDemoExample() {
        this(null);
    }
    
    /**
     * 运行完整的系统演示
     */
    public void runCompleteDemo() {
        System.out.println("🚀 启动AI增强案卷文书处理系统演示");
        System.out.println("=" .repeat(60));
        
        // 打印配置信息
        config.printConfiguration();
        
        // 验证配置
        if (!config.validateConfiguration()) {
            System.err.println("❌ 配置验证失败，请检查配置文件");
            return;
        }
        
        try {
            // 1. 系统健康检查
            demoSystemHealthCheck();
            
            // 2. 单文档处理演示
            demoSingleDocumentProcessing();
            
            // 3. 批量文档处理演示
            demoBatchDocumentProcessing();
            
            // 4. 自然语言交互演示
            demoNaturalLanguageInterface();
            
            // 5. 性能优化演示
            demoPerformanceOptimization();
            
        } catch (Exception e) {
            System.err.println("❌ 演示过程中发生错误: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭系统
            systemIntegrator.shutdown();
        }
    }
    
    /**
     * 演示系统健康检查
     */
    private void demoSystemHealthCheck() {
        System.out.println("\n🔍 1. 系统健康检查演示");
        System.out.println("-".repeat(40));
        
        CompletableFuture<SystemHealthReport> healthFuture = 
            systemIntegrator.performSystemHealthCheck();
        
        try {
            SystemHealthReport healthReport = healthFuture.get();
            
            System.out.println("检查时间: " + healthReport.getCheckTime());
            System.out.println("整体健康状态: " + healthReport.getOverallHealth().getDescription());
            System.out.println("API连接状态: " + (healthReport.isApiConnected() ? "✅ 已连接" : "❌ 未连接"));
            
            if (healthReport.getComponentHealth() != null) {
                System.out.println("\n组件健康状态:");
                healthReport.getComponentHealth().forEach((component, health) -> {
                    System.out.println("  " + component + ": " + health.getStatus().getDescription());
                });
            }
            
        } catch (Exception e) {
            System.err.println("健康检查失败: " + e.getMessage());
        }
    }
    
    /**
     * 演示单文档处理
     */
    private void demoSingleDocumentProcessing() {
        System.out.println("\n📋 2. 单文档处理演示");
        System.out.println("-".repeat(40));
        
        // 创建示例文档
        CaseDocument testDocument = createSampleCaseDocument();
        ProcessingOptions options = new ProcessingOptions();
        options.setEnableAIEnhancement(true);
        options.setEnableQualityCheck(true);
        options.setGenerateDetailedReport(true);
        
        System.out.println("处理文档: " + testDocument.getDocumentId());
        System.out.println("文档类型: " + testDocument.getDocumentType().getDescription());
        System.out.println("总页数: " + testDocument.getTotalPages());
        
        CompletableFuture<CompleteProcessingResult> processingFuture = 
            systemIntegrator.processCompleteCase(testDocument, options);
        
        try {
            CompleteProcessingResult result = processingFuture.get();
            
            System.out.println("\n处理结果:");
            System.out.println("  处理状态: " + (result.isSuccess() ? "✅ 成功" : "❌ 失败"));
            System.out.println("  处理时间: " + 
                java.time.Duration.between(result.getStartTime(), result.getEndTime()).toMillis() + "ms");
            
            if (result.getDocumentSegments() != null) {
                System.out.println("  分割段落数: " + result.getDocumentSegments().size());
            }
            
            if (result.getQualityAssessment() != null) {
                QualityAssessmentResult quality = result.getQualityAssessment();
                System.out.println("  整体质量评分: " + String.format("%.1f%%", quality.getOverallQualityScore() * 100));
                System.out.println("  质量等级: " + quality.getQualityLevel());
            }
            
            if (result.getProcessingReport() != null) {
                ProcessingReport report = result.getProcessingReport();
                System.out.println("  高风险问题数: " + report.getHighRiskIssues());
            }
            
        } catch (Exception e) {
            System.err.println("文档处理失败: " + e.getMessage());
        }
    }
    
    /**
     * 演示批量文档处理
     */
    private void demoBatchDocumentProcessing() {
        System.out.println("\n📚 3. 批量文档处理演示");
        System.out.println("-".repeat(40));
        
        // 创建批量文档
        List<CaseDocument> batchDocuments = createSampleBatchDocuments(5);
        BatchProcessingOptions batchOptions = new BatchProcessingOptions();
        batchOptions.setBatchSize(3);
        batchOptions.setMaxConcurrency(2);
        batchOptions.setEnableProgressTracking(true);
        
        System.out.println("批量处理文档数: " + batchDocuments.size());
        System.out.println("批次大小: " + batchOptions.getBatchSize());
        System.out.println("最大并发数: " + batchOptions.getMaxConcurrency());
        
        CompletableFuture<BatchProcessingResult> batchFuture = 
            systemIntegrator.processBatchCases(batchDocuments, batchOptions);
        
        try {
            BatchProcessingResult batchResult = batchFuture.get();
            
            System.out.println("\n批量处理结果:");
            System.out.println("  总文档数: " + batchResult.getTotalDocuments());
            System.out.println("  成功处理: " + batchResult.getSuccessCount());
            System.out.println("  处理失败: " + batchResult.getFailureCount());
            System.out.println("  成功率: " + String.format("%.1f%%", 
                (double) batchResult.getSuccessCount() / batchResult.getTotalDocuments() * 100));
            
            if (batchResult.getStatistics() != null) {
                BatchStatistics stats = batchResult.getStatistics();
                System.out.println("  平均处理时间: " + String.format("%.2fs", stats.getAverageProcessingTime()));
                System.out.println("  平均质量评分: " + String.format("%.1f%%", stats.getAverageQualityScore() * 100));
            }
            
        } catch (Exception e) {
            System.err.println("批量处理失败: " + e.getMessage());
        }
    }
    
    /**
     * 演示自然语言交互
     */
    private void demoNaturalLanguageInterface() {
        System.out.println("\n🤖 4. 自然语言交互演示");
        System.out.println("-".repeat(40));
        
        String sessionId = "demo_session_" + System.currentTimeMillis();
        
        // 准备上下文
        Map<String, Object> context = new HashMap<>();
        context.put("current_document", createSampleCaseDocument());
        
        // 测试不同类型的查询
        String[] testQueries = {
            "请帮我分析这个文档的分割质量如何？",
            "这个案卷的合规性风险等级是什么？",
            "能给我一些改进文档质量的建议吗？",
            "AI系统的文档分割原理是什么？"
        };
        
        for (String query : testQueries) {
            System.out.println("\n用户查询: " + query);
            
            CompletableFuture<ConversationResponse> responseFuture = 
                systemIntegrator.processNaturalLanguageQuery(sessionId, query, context);
            
            try {
                ConversationResponse response = responseFuture.get();
                
                System.out.println("响应类型: " + response.getResponseType().getDescription());
                System.out.println("置信度: " + String.format("%.1f%%", response.getConfidence() * 100));
                System.out.println("回复内容: " + response.getResponseText().substring(0, 
                    Math.min(200, response.getResponseText().length())) + "...");
                
                if (response.getActionSuggestions() != null && !response.getActionSuggestions().isEmpty()) {
                    System.out.println("操作建议:");
                    response.getActionSuggestions().forEach(suggestion -> 
                        System.out.println("  - " + suggestion.getActionText()));
                }
                
            } catch (Exception e) {
                System.err.println("查询处理失败: " + e.getMessage());
            }
        }
    }
    
    /**
     * 演示性能优化
     */
    private void demoPerformanceOptimization() {
        System.out.println("\n⚡ 5. 性能优化演示");
        System.out.println("-".repeat(40));
        
        PerformanceOptimizationResult optimizationResult = 
            systemIntegrator.optimizeSystemPerformance();
        
        System.out.println("优化时间: " + optimizationResult.getOptimizationTime());
        System.out.println("预期性能提升: " + String.format("%.1f%%", 
            optimizationResult.getExpectedImprovement() * 100));
        
        if (optimizationResult.getOptimizationActions() != null) {
            System.out.println("\n优化操作:");
            optimizationResult.getOptimizationActions().forEach(action -> {
                System.out.println("  - " + action.getActionType() + ": " + action.getDescription());
                System.out.println("    预期影响: " + String.format("%.1f%%", action.getExpectedImpact() * 100));
            });
        }
        
        if (optimizationResult.getOptimizationSummary() != null) {
            System.out.println("\n优化总结: " + optimizationResult.getOptimizationSummary());
        }
    }
    
    // ============ 辅助方法 ============
    
    /**
     * 创建示例案卷文档
     */
    private CaseDocument createSampleCaseDocument() {
        CaseDocument document = new CaseDocument();
        document.setDocumentId("DEMO_DOC_" + System.currentTimeMillis());
        document.setDocumentType(DocumentType.CASE_FILE);
        document.setTitle("某公司环保违法案件处理材料汇编");
        document.setTotalPages(15);
        document.setContent(generateSampleContent());
        document.setImageUrls(Arrays.asList(
            "demo_image_1.jpg",
            "demo_image_2.jpg"
        ));
        return document;
    }
    
    /**
     * 创建批量示例文档
     */
    private List<CaseDocument> createSampleBatchDocuments(int count) {
        List<CaseDocument> documents = new ArrayList<>();
        DocumentType[] types = {DocumentType.CASE_FILE, DocumentType.EVIDENCE, 
                              DocumentType.INVESTIGATION_RECORD, DocumentType.DECISION_DOCUMENT};
        
        for (int i = 0; i < count; i++) {
            CaseDocument doc = new CaseDocument();
            doc.setDocumentId("BATCH_DOC_" + i + "_" + System.currentTimeMillis());
            doc.setDocumentType(types[i % types.length]);
            doc.setTitle("批量处理文档 " + (i + 1));
            doc.setTotalPages(5 + i * 2);
            doc.setContent("这是第 " + (i + 1) + " 个批量处理的示例文档内容...");
            documents.add(doc);
        }
        
        return documents;
    }
    
    /**
     * 生成示例文档内容
     */
    private String generateSampleContent() {
        return """
                行政处罚决定书
                
                被处罚人：某环保科技有限公司
                法定代表人：张某某
                地址：某市高新技术开发区创新路88号
                
                违法事实：
                经查，该公司在2023年3月至6月期间，未按照环保要求处理工业废水，
                直接排放至市政管网，造成严重环境污染。
                
                法律依据：
                根据《中华人民共和国环境保护法》第六十一条、第六十二条规定...
                
                处罚决定：
                1. 责令立即停止违法行为
                2. 限期改正违法行为
                3. 处罚款人民币50万元
                
                执法机关：某市生态环境局
                执法人员：李某某、王某某
                日期：2024年01月15日
                
                [印章位置]
                """;
    }
    
    /**
     * 主方法 - 运行演示
     */
    public static void main(String[] args) {
        // 支持多种配置方式：
        // 1. 命令行参数: java SystemDemoExample your_api_key
        // 2. 环境变量: SILICONFLOW_API_KEY=your_api_key
        // 3. 配置文件: ai-config.properties
        
        String apiKey = null;
        
        // 1. 检查命令行参数
        if (args.length > 0) {
            apiKey = args[0];
            System.out.println("🔑 使用命令行参数提供的API密钥");
        }
        
        // 2. 检查环境变量
        if (apiKey == null || apiKey.trim().isEmpty()) {
            apiKey = System.getenv("SILICONFLOW_API_KEY");
            if (apiKey != null && !apiKey.trim().isEmpty()) {
                System.out.println("🔑 使用环境变量提供的API密钥");
            }
        }
        
        // 3. 使用配置文件
        if (apiKey == null || apiKey.trim().isEmpty()) {
            AIConfig config = AIConfig.getInstance();
            apiKey = config.getApiKey();
            if (apiKey != null && !"your_api_key_here".equals(apiKey)) {
                System.out.println("🔑 使用配置文件提供的API密钥");
            }
        }
        
        // 验证API密钥
        if (apiKey == null || apiKey.trim().isEmpty() || "your_api_key_here".equals(apiKey)) {
            System.out.println("⚠️  未找到有效的API密钥，请通过以下方式之一设置：");
            System.out.println("   1. 命令行参数: java SystemDemoExample your_api_key");
            System.out.println("   2. 环境变量: export SILICONFLOW_API_KEY=your_api_key");
            System.out.println("   3. 配置文件: 修改 ai-config.properties 中的 siliconflow.api.key");
            System.out.println("🔄 运行模拟演示模式...\n");
        }
        
        SystemDemoExample demo = new SystemDemoExample(apiKey);
        demo.runCompleteDemo();
    }
}